import {
  CanActivate,
  ExecutionContext,
  Inject,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { JwtService } from '@nestjs/jwt';
import { Request, Response } from 'express';
import { Observable } from 'rxjs';

interface JwtUserData {
  userId: number;
  username: string;
  exp?: number;
}

declare module 'express' {
  interface Request {
    user: JwtUserData;
  }
}
@Injectable()
export class AuthGuard implements CanActivate {
  @Inject() private reflector: Reflector;
  @Inject(JwtService) private jwtService: JwtService;
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const request: Request = context.switchToHttp().getRequest();
    const response: Response = context.switchToHttp().getResponse();

    const requireLogin = this.reflector.getAllAndOverride('require-login', [
      context.getHandler(),
      context.getClass(),
    ]);

    if (!requireLogin) return true;

    const authorization = request.headers.authorization;
    if (!authorization) {
      throw new UnauthorizedException('用户未登录');
    }
    try {
      const token = authorization.split(' ')[1]; // 'Bearer jwt_token'
      const data = this.jwtService.verify<JwtUserData>(token);

      const user = {
        userId: data.userId,
        username: data.username,
      };
      request.user = user;

      //过期时间小于一天就刷新token
      const exp = data?.exp;
      const nowTime = Math.floor(Date.now() / 1000);
      const refreshTokenTime = exp - nowTime;
      if (refreshTokenTime < 60 * 60 * 24) {
        response.header(
          'token',
          this.jwtService.sign(user, {
            expiresIn: '7d',
          }),
        );
      }

      return true;
    } catch (e) {
      throw new UnauthorizedException('token 失效，请登录');
    }
  }
}
